<template>
    <div class="chart-div" style="position:relative">
        <div style="position:absolute;right:10px;top:5px;z-index:1000">
            {{testShow}}
            <exSwitch v-model="isShowGt" label="港通" size="mini" @change="onRefresh" v-if="isGt"></exSwitch>
            <el-button icon="el-icon-refresh" size="mini" type="text" @click="onRefresh" title="刷新"></el-button>
            <el-button icon="el-icon-search" size="mini" type="text" @click="showDialog" title="大图查看"></el-button>
        </div>
        
        
        <chartCom ref="curchart" :chrCfg="chrCfg" :size="size"></chartCom>
        
        <chartDialog ref="chrWin" title="" :chrCfg="chrCfg"></chartDialog>
    </div>

</template>

<script>

import chartCom from "./chartCommon.vue";
import chartDialog from "./chartDialog.vue";
export default {
    components:{
        chartCom,
        chartDialog
    },
    props:["code","list","isGt","size","isAddEvent","pre"], //isGt 0不显示 1默认不查询 2默认查询   isAddEvent: 是否判断事件
    inject: ['cfg',"isQry","getSleepTime","isMoneyException","addException"],
    data(){
        var that = this;
        return{
            curDate: this.$dayjs().format("MM-DD"),
            isShowGt: this.isGt==2?true:false,
            timeArr:[],
            maxRate: 0,
            maxGt: 0,
            yStep : 1,
            gtList: [],

            chrCfg:{
                // dataZoom : [ { type : 'inside'}],
                title:{
                    top: '78%',
                    left: 'center',
                    text: '成交量',
                    textStyle:{
                        fontSize: 12,
                        fontWeight: "normal"
                    }
                },
                grid:[{
                    left: '100px',
                    top: '40px',
                    bottom: '28%'
                }, {
                    left: '100px',
                    top: '80%',
                    bottom: '20px',
                }],
                legend : {
                    data : [],
                    left: 10
                },
                axisPointer: {
                    link: {xAxisIndex: 'all'},
                    label: {
                        backgroundColor: '#777'
                    }
                },
                xAxis:[
                    {
                        type : 'category',
                        boundaryGap: true,
                        gridIndex: 0,
                        // name : 'Time',
                        // data : [],
                        axisLabel: {
                            interval: (idx,value)=>{
                                if(idx==0 || idx==60 || idx==120 || idx==180 || idx==240) return true;
                                return false;
                            },
                            // rotate:40
                        },
                        axisTick:{
                            show: true,
                            alignWithLabel: true,
                            interval: 60,
                        },
                        splitLine: {
                            show: true,
                            interval: 60,
                            lineStyle: {
                                color: '#ccc',
                                type: 'dott',
                            }
                        },
                    },{
                        type : 'category',
                        // data: [],
                        axisLabel: {
                            interval: (idx,value)=>{
                                if(idx==0 || idx==60 || idx==120 || idx==180 || idx==240) return true;
                                return false;
                            },
                            // rotate:40
                        },
                        axisTick:{
                            show: true,
                            alignWithLabel: true,
                            interval: 60,
                        },
                        splitLine: {
                            show: true,
                            interval: 60,
                            lineStyle: {
                                color: '#ccc',
                                type: 'dott',
                            }
                        },
                        gridIndex: 1
                    },{
                        type : 'category',
                        gridIndex: 0
                    }
                ],
                yAxis:[
                    {
                        splitLine: {show: false}
                    }, {
                        splitLine: {show: false},
                        gridIndex: 1
                    }, {
                        splitLine: {show: false}
                    }
                ],
                tooltip : {
                    trigger : 'axis',
                    formatter(datas){
                        var res = datas[0].name + '<br/>'
                        for (var i = 0, length = datas.length; i < length; i++) {
                            var item = datas[i];
                            var value = item.data;
                            if(item.seriesName=="港通"){
                                res += datas[i].marker+ datas[i].seriesName + '：' 
                                    +value+ '亿<br/>'
                            }else{
                                var curCode = that.codeList.filter((a)=>{return item.seriesName.indexOf(a.name)!=-1})
                                if(curCode.length>0){
                                    curCode = curCode[0];
                                    var price = curCode.priceArr[item.dataIndex]
                                    res += datas[i].marker+ datas[i].seriesName + '：' 
                                        + price +"("+value+"%)"+ '<br/>'
                                }else{
                                    res += datas[i].marker+ datas[i].seriesName + '：' 
                                        + value+ '<br/>'
                                }
                            }
                        }
                        return res
                    }
                },
                // series:[],
                // tooltipFormatter(idx){
                //     if(!that.chartDatas) return;
                //     var dateitem = that.chartDatas[idx];
                //     var info=
                //      '玩家 : '+dateitem.nickname + '<br/>'
                //     + '玩家ID : '+dateitem.playerNo + '<br/>'
                //     + '投注 : '+dateitem.bet + '<br/>'
                //     + '盈亏 : '+dateitem.integralResult + '<br/>'
                //     + '摇奖结果 : '+that.$dict.tranDict("dbdict.millionSlot",dateitem.drawType) + '<br/>';
                //     return info;
                // }
            },

            curchart : null,
            bigChart : null,
            isShowWin : false,
            testShow : "",
            eventInfo: {},
        }
    },
    computed:{
        codeList(){
            var list = [];
            if(this.code){
                list.push({code:this.code,pre:this.pre||"",name:"",prePrice:0,rateArr:[],priceArr:[],numArr:[]})
            }
            if(this.list){
                this.list.map(item=>{
                    list.push({code:item.code,pre:item.pre||this.pre,name:"",prePrice:0,rateArr:[],priceArr:[],numArr:[]})
                })
            }
            return list || [];
        }
    },
    mounted(){
        this.curchart = this.$refs.curchart;
        this.initXArr();
        this.getLineData();
    },
    methods:{
        onRefresh(){
            this.curchart.clearChartData();
            this.getLineData();
        },
        clearChartData(){
            this.curchart.clearChartData();
        },
        getLineData(){
            this.maxRate = 0;
            this.maxGt =0;
            if(!this.codeList) return;
            var len = this.codeList.length;
            if(len==0){
                this.setCharInfo()
                return;
            }
            this.getStockLineInfo(this.codeList[0],1)
        },
        reDraw(){
            this.$nextTick(()=>{
                if(this.$refs.curchart) this.$refs.curchart.reDraw();
            });
        },
        setCharInfo(){
            var that = this;
            this.chrCfg.series=[];
            this.chrCfg.legend.data=[];
            this.chrCfg.yAxis = [];
            this.codeList.map((item,idx)=>{
                var showName = item.name;
                if(this.codeList.length==1){
                    showName= item.name+"("+item.code+")";
                }
                this.chrCfg.legend.data.push(showName);
                var seriescfg={
                    symbolSize: 0,
                    name : showName,
                    type : 'line',
                    smooth : false,
                    // smoothMonotone : "x",
                    data : item.rateArr,
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                    itemStyle: {
                        normal: {
                            // color: '#6cb041',
                            lineStyle:{
                                width:1//设置线条粗细
                            }
                        }
                    },
                    markLine:{
                        symbol: ['none', 'none'],
                        itemStyle:{
                            normal:{
                                label:{
                                    show: false,
                                }
                            }
                        },
                        data:[{yAxis :0}]
                    }
                }
                this.chrCfg.series.push(seriescfg);
            });
            this.chrCfg.yAxis.push(
                {
                    type : 'value',
                    name : "",
                    min : "value",
                    boundaryGap: true,
                    // splitNumber: 4,
                    interval:that.yStep,
                    gridIndex: 0,
                    min: function (value) {
                        return 0-that.maxRate;
                    },
                    max: function (value) {
                        return that.maxRate;
                    },
                    // axisLine: {show:true},
                    // axisTick: {show:true},
                    splitLine:{
                        show:true,
                        lineStyle: {
                            color: '#ccc',
                            type: 'dott',
                        }},
                    show:true,
                    axisLabel: {
                        show:true,
                        rotate:0,
                        formatter: (value, index)=> {
                            if(that.codeList.length==0){
                                return value;
                            }
                            var price =  that.codeList[0].prePrice;
                            var name = (price*(1+value*1/100)).toFixed(2)+"("+value.toFixed(2)+"%)";;
                            return name;
                        }
                    }
                }
            );
            this.setTradeNum()
            if(this.isShowGt && this.gtList &&  this.gtList.length>1 && that.maxGt!=0){
                this.chrCfg.legend.data.push("港通");
                var seriescfg1={
                    name : "港通",
                    type : 'line',
                    smooth : false,
                    symbolSize: 0,
                    // smoothMonotone : "x",
                    data : this.gtList,
                    // xAxisIndex: 0,
                    yAxisIndex: 2,
                    itemStyle: {
                        normal: {
                            // color: '#6cb041',
                            lineStyle:{
                                width:1//设置线条粗细
                            }
                        }
                    },
                }
                this.chrCfg.series.push(seriescfg1);
                
                this.chrCfg.yAxis.push(
                    {
                        name: '港通',
                        nameLocation: 'center',
                        type: 'value',
                        // splitNumber: 2,
                        interval:that.maxGt/2,
                        axisLabel: {
                            // rotate:40
                        },
                        gridIndex: 0,
                        min: function (value) {
                            return 0-that.maxGt;
                        },
                        max: function (value) {
                            return that.maxGt;
                        },
                        // inverse: true
                    }
                );
            }
            // var last = this.codeList[0].priceArr;
            // this.testShow=last[last.length-1];
            this.reDraw();
        },

        setTradeNum(){
            var first = this.codeList[0];
            if(!first || !first.numArr) return;
            if(first.numArr.length==0) return;
            // var name = first.name+"交易量";
            // this.chrCfg.legend.data.push(name);
            
            this.chrCfg.yAxis.push(
                {
                    name:"",
                    nameLocation: 'end',
                    splitNumber: 2,
                    gridIndex: 1
                }
            );
            var seriescfg={
                name : "成交量",
                type : 'bar',
                data : first.numArr,
                xAxisIndex: 1,
                yAxisIndex : 1,
                itemStyle:{
                    color:"red"
                }
            }
            this.chrCfg.series.push(seriescfg);

        },
        
        getStockLineInfo(item,qryIdx){
            var code = item.code;
            var that = this;
            var first = code.substring(0,1);
            if(item.pre){
                code = item.pre+"."+item.code
            }else if(first=="0" || first=="3" || first=="1"){
                code = "0."+code;
            }else {
                code = "1."+code;
            }
            item.priceArr=[];
            item.rateArr=[];
            if(qryIdx==1)item.numArr = [];
            if(this.curchart){
                var option = this.curchart.getOption();
                if(option.legend[0].selected[item.name]===false){
                    if(qryIdx==this.codeList.length){
                        // debugger;
                        this.yStep = this.maxRate/2;
                        if(this.isShowGt){
                            this.getGtList();
                        }else{
                            this.setCharInfo();
                        }
                    }else{
                        this.getStockLineInfo(this.codeList[qryIdx],qryIdx+1)
                    }
                    return;
                }
            }

            this.$axios.get(`http://push2.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ut=fa5fd1943c7b386f172d6893dbfba10b&ndays=1&iscr=0&iscca=0&secid=${code}`)
            .then((res) => {
                if (res.data.data) {
                    item.prePrice = res.data.data.prePrice;
                    item.name = res.data.data.name;
                    item.code = res.data.data.code;
                   
                    var list = res.data.data.trends || [];
                    var len = list.length;
                    if(this.isAddEvent){
                        if(len>5){
                            var last = list[len-1].split(",")[5];
                            var isEvent = true;
                            if(this.cfg.event.chart_time_num){
                                if(last<(this.cfg.event.chart_time_num_min || 100)) isEvent = false; //交易量少于100,都不算放量
                                if(item.bigTradeTime){
                                    var cur =  new Date().getTime();
                                    if(cur-item.bigTradeTime<40000) isEvent=false;
                                };
                                for(var i=len-2;i>len-5;i--){
                                    if(!isEvent) break;
                                    var pre = list[i].split(",")[5];
                                    if(last/pre<(this.cfg.event.chart_time_num_bet || 2.5)){
                                        isEvent = false;
                                        break;
                                    }
                                }
                                //再增加一个最后时段内连续上涨了指定幅度(不算时长)
                                


                                if(isEvent){
                                    var lastitem = list[len-1].split(",");
                                    var wave = this.getRise(lastitem[1],item.prePrice)
                                    var msg = `<span class='blue'>${item.name}&nbsp;(${item.code})<br/>${lastitem[0]}<br/>&nbsp;&nbsp;&nbsp;&nbsp;curwave:&nbsp;&nbsp;${wave}%<br/>分时放量ing&nbsp;${last}</span>`
                                    if(this.addException(msg,wave>0)){
                                        item.bigTradeTime = new Date().getTime();
                                    }
                                }
                            }
                            if(this.cfg.event.chart_time_range){
                                var timaRange = this.cfg.event.chart_time_range_minute || 20;                                
                                if(len>timaRange && !isEvent){
                                    var isMax = true,isMin=true;
                                    
                                    if(item.rangeEventTime){
                                        var cur =  new Date().getTime();
                                        if(cur-item.rangeEventTime<10*60000){  //10分钟内不重复
                                            isMax = false;
                                            isMin = false;
                                        }
                                    };

                                    var lastitem = list[len-1].split(",");
                                    var lastprice = lastitem[2];
                                    for(var i=len-2;i>len-timaRange-1;i--){
                                        if(!isMax && !isMin) break;
                                        var pre = list[i].split(",")[2];
                                        if(isMin && lastprice>=pre){
                                            isMin = false;
                                        }
                                        if(isMax && lastprice<=pre){
                                            isMax = false;
                                        }
                                    }
                                    
                                    if(isMax || isMin){
                                        var name = "新高";
                                        var color= "red";
                                        if(isMin){
                                            name = "新低";
                                            color = "green";
                                        }
                                        var msg = `<span class='${color}'>${item.name}&nbsp;(${item.code})<br/>${lastitem[0]}<br/>&nbsp;&nbsp;cur:${lastprice}<br/>${timaRange}分钟${name}&nbsp;</span>`
                                        if(this.addException(msg)){
                                            item.rangeEventTime = new Date().getTime();
                                        }
                                    }
                                }
                            }


                        }
                    }
                    list.map((row,idx)=>{
                        var tmp = row.split(",");
                        //tmp  1: 开始 2: 结束 3:最高 4:最低
                        var price = tmp[2];
                        var max = tmp[3];
                        var min = tmp[4];
                        var priceRate = this.getRise(price,item.prePrice)
                        var maxRate = Math.abs(this.getRise(max,item.prePrice))
                        var minRate = Math.abs(this.getRise(min,item.prePrice))
                        if(maxRate<minRate) maxRate = minRate;
                        if(this.maxRate<maxRate){
                            this.maxRate = maxRate;
                        }
                        item.priceArr.push( price);
                        item.rateArr.push( priceRate);
                        
                        if(qryIdx==1){
                            item.numArr.push(tmp[5]);
                            this.chrCfg.title.text = item.name+"成交量"
                        }
                    })

                    if(qryIdx==this.codeList.length){
                        // debugger;
                        this.yStep = this.maxRate/2
                        if(this.isShowGt){
                            this.getGtList();
                        }else{
                            this.setCharInfo();
                        }
                    }else{
                        this.getStockLineInfo(this.codeList[qryIdx],qryIdx+1)
                    }
                } else {
                    this.$message.error("请求失败:"+res.data.message);
                }
            })
        },
        getGtList(){
            this.gtList = [];
            this.$axios.get("http://push2.eastmoney.com/api/qt/kamt.rtmin/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54,f55,f56").then((res) => {
                if(res.data && res.data.data && res.data.data.s2n){
                    var datas = res.data.data.s2n;
                    if(res.data.data.s2nDate!=this.curDate){
                        this.setCharInfo();
                        return;
                    }
                    var list = [];
                    datas.map((item)=>{
                        var arr = item.split(",")
                        if(arr.length<2 || isNaN(arr[1])) return;
                        var item = {
                            col1: arr[0],
                            col2: this.formatWanMoney(arr[1]),
                            col3: this.formatWanMoney(arr[3]),
                            col4: this.formatWanMoney(arr[5]),
                        };
                        
                        var maxGt = Math.abs(item.col4)
                        if(this.maxGt<maxGt){
                            this.maxGt = maxGt;
                        }
                        list.push(item.col4);
                    });
                    this.gtList = list;
                    this.setCharInfo();
                }else{
                    this.$message.error(JSON.stringify(res.data));
                }
            })
        },
        closeDialog(){
            this.isShowWin = false;
        },
        showDialog(){
            this.$refs.chrWin.showWin()
        },
        initXArr(){
            this.addXarr(930,30)
            this.addXarr(1000,60)
            this.addXarr(1100,31)
            this.addXarr(1301,59)
            this.addXarr(1400,60)
            this.addXarr(1500,1)
            this.chrCfg.xAxis[0].data = this.timeArr;
            this.chrCfg.xAxis[1].data = this.timeArr;
        },
        addXarr(start,num){
            for(var i=0;i<num;i++){
                var time = start+i;
                time= time+"";
                if(time.length<4) time="0"+time;
                time = time.substring(0,2)+":"+time.substring(2,4);
                // console.info(time);
                this.timeArr.push(time);
            }
        },
    }
}
</script>

<style lang="less" scope>

.chart-div{
    border:1px lightgray solid;
    display: inline-block;
    // margin-bottom: 5px;
}

</style>